<template>
  <page-header-wrapper>
    <a-card title="供应商&经销商">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.keyword" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" :loading="loading" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建供应商&经销商</a-button>
        <a-button type="primary" @click="handleFinance">财务统计</a-button>
        <a-button type="primary" @click="handleRecord">账务记录</a-button>
        <a-button type="primary" @click="handleMerge">合并供应商</a-button>
        <!-- <a-button icon="cloud-upload" @click="handleAdd">导出</a-button> -->
      </div>

      <a-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :loading="loading"
        :data-source="loadData"
        :pagination="pagination"
        :scroll="{ x: `${columns.length}0%`}"
        :footer="loadData.length === 11 ? handleFooterShow :null"
        @change="handleTableChange"
      >
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#2db7f5" v-if="record?.status == 1">合作中</a-tag>
            <a-tag color="#f50" v-if="record?.status == 0">停止合作</a-tag>
          </template>
        </span>
        <span slot="types" slot-scope="text, record">
          <template>
            <div v-if="record?.types === '1'">供应商</div>
            <div v-if="record?.types === '2'">经销商</div>
            <div v-if="record?.types === '3'">供应商&经销商</div>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template v-if="record.id !== '合计'">
            <a-tag color="#428bca" @click="handleDetail(record)">进入</a-tag>
          </template>
        </span>
      </a-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
// import moment from 'moment'
import { Ellipsis } from '@/components'
import {
  getSuppliesListByTypeUsingPOST,
  updateSuppliesUsingPOST,
  addSuppliesUsingPOST,
  exportSupplyListUsingPOST
} from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
import CreateForm from './edit'
export default {
  name: 'AgentIndex',
  components: {
    Ellipsis,
    CreateForm,
  },
  data() {
    return {
      columns: [
        {
          title: 'ID',
          with: 200,
          dataIndex: 'id',
        },
        {
          title: '名称',
          with: 120,
          dataIndex: 'name',
        },
        {
          title: '类型',
          with: 120,
          dataIndex: 'types',
          scopedSlots: { customRender: 'types' },
        },
        {
          title: '状态',
          with: 120,
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '结余(元)',
          with: 120,
          dataIndex: 'curAmount',
        },
        {
          title: '待上账(元)',
          with: 120,
          dataIndex: 'waitAmount',
        },
        {
          title: '库存成本(元)',
          with: 120,
          dataIndex: 'inventoryCost',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // create model
      visible: false,
      footerDataSource: [],
      loading: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        pageNo: 1,
        pageSize: 10,
        queryCondition: '',
        status: '',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      pagination: {},
    }
  },
  created() {
    this.handleSearch(this.queryParam)
  },
  methods: {
    handleExpert(params){
      exportSupplyListUsingPOST({ ...params, }).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '供应商&经销商列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    handleFooterShow() {
      if (this.footerDataSource.length > 0) {
        return (
          <a-table
            ref="table"
            size="default"
            rowKey={Math.random}
            pagination={false}
            columns={this.columns}
            dataSource={this.footerDataSource}
            showHeader={false}
            class="j-table-force-nowrap"
          ></a-table>
        )
      }
    },
    handleSearch(params) {
      this.loading = true
      getSuppliesListByTypeUsingPOST(params)
        .then((res) => {
          this.loading = false
          this.loadData = res.data.list.map((item)=>{return {...item,id:item.id ?? '合计'}})
          this.footerDataSource = [{...res.data.list[res.data.list.length - 1],id:'合计'}]
          this.queryParam.pageNo = this.pagination.current
          this.pagination = { ...this.pagination, total: Number(res.data.total) }
        })
        .catch((error) => {
          this.loading = false
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        queryCondition: this.queryParam.queryCondition,
        status: this.queryParam.status,
        date: this.queryParam.date,
        pageNo: pagination.current,
        pageSize: pagination.pageSize,
      })
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleDetail(record) {
      this.$router.push({ path: `/agent/${record?.id}` })
    },
    handleFinance() {
      this.$router.push({ path: `/agent/finance` })
    },
    handleRecord() {
      this.$router.push({ path: `/agent/record` })
    },
    handleMerge() {
      this.$router.push({ path: `/agent/merge` })
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (!!values.id) {
            // 修改 e.g.
            updateSuppliesUsingPOST({ ...values })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
              })
              .catch((error) => {
                this.confirmLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            // 新增
            addSuppliesUsingPOST({ ...values, status: 1 })
              .then(() => {
                this.handleSearch(this.queryParam)
                this.$message.success('操作成功')
                this.visible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
              })
              .catch((error) => {
                this.confirmLoading = false
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
}
</script>
<style lang="less" scoped>
    /deep/ .ant-table-content .ant-table-body{
    position: relative;
    z-index: 2;
    background: #FFFFFF;
    }
    /deep/ .ant-table-footer .ant-table-body{
      overflow: hidden !important;
      position: relative !important;
      z-index: 1 !important;
    }
    /deep/ .ant-table-content > .ant-table-footer {
    padding: 0 !important;
    top: -47px;
    position: relative;
    z-index: 0;
    }
</style>